package com.jieshuibao.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.PolicyExample;
import com.jieshuibao.model.db.PolicyExample.Criteria;
import com.jieshuibao.model.db.Policy;
import com.jieshuibao.model.db.QuestionUserEx;
import com.jieshuibao.model.db.QuestionUserExample;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.UserSearch;
import com.jieshuibao.model.db.Video;
import com.jieshuibao.model.db.VideoExample;
import com.jieshuibao.model.domain.Article;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.PagePhone;
import com.jieshuibao.model.domain.PageRequest;
import com.jieshuibao.model.domain.SearchResponse;
import com.jieshuibao.model.domain.UserLevel;
import com.jieshuibao.service.AnswerUserService;
import com.jieshuibao.service.ArticelService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.PolicyService;
import com.jieshuibao.service.QuestionExService;
import com.jieshuibao.service.QuestionUserService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.VideoService;
import com.jieshuibao.util.DeleteHtmlUtil;

@Controller
@RequestMapping(value="/search")
public class SearchController {
	private static final Logger logger = LoggerFactory
			.getLogger("SearchController.class");

	private static final ObjectMapper mapper = new ObjectMapper();
	@Resource
	private RedisService redisService;
	
	@Resource
	private ArticelService articelService;
	
	@Resource
	private CounselorDutyService counselorDutyService;
	
	@Resource
	private QuestionExService questionExService;
	
	@Resource
	private QuestionUserService questionUserService;
	
	@Resource
	private AnswerUserService answerUserService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private PolicyService policyService;
	
	@Resource
	private VideoService videoService;
	
	@RequestMapping(value = "/all", method = RequestMethod.POST)
	@ResponseBody
	public Object searchAll(HttpServletRequest request,
			@RequestBody PagePhone pagePhone) {
		SearchResponse searchResponse = new SearchResponse();
		try {

			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						String search = pagePhone.getSearch();
						if(search!=null){
							PagePhone pagePhone2 = new PagePhone();
							pagePhone2.setSearch(search);
							pagePhone2.setPageIndex(0);
							pagePhone2.setPageSize(3);
							List<Article> articles = articelService.getArticleByTitle(pagePhone2);
							if (articles != null) {
								for (Article article : articles) {
									String descriptionHtml = article.getDescription();
									if(descriptionHtml!=null&&!descriptionHtml.equals("")){
										String description = DeleteHtmlUtil.getTextFromHtml(descriptionHtml);
										article.setDescription(description);
									}
									UserLevel userLevel = article.getUserLevel();
									if (userLevel != null) {
										String counselorDuty = userLevel
												.getCounselorDuty();
										if (counselorDuty != null
												&& !counselorDuty.equals("")) {
											if (!counselorDuty.contains(" ")) {
												StringBuilder stringBuilder = new StringBuilder();
												String[] split = counselorDuty
														.split(",");
												if(split!=null){
													
													for (String id : split) {
														if (id != null
																&& !id.equals("")) {
															Duty duty = counselorDutyService
																	.getDutyById(id);
															if (duty != null) {
																
																stringBuilder
																.append(duty
																		.getDutyName()
																		+ " ");
															}
														}
														
													}
													userLevel
													.setCounselorDuty(stringBuilder
															.toString());
												}
											}
										}

										article.setUserLevel(userLevel);
									}
								}
								searchResponse.setArticles(articles);
								
							}
							
							List<QuestionUserEx> questions = questionExService.getQuestionByContent(pagePhone2);
							if(questions!=null){
								
								for (QuestionUserEx question : questions) {
									QuestionUserExample questionUserExample2 = new QuestionUserExample();
									QuestionUserKey questionUserKey2 = new QuestionUserKey();
									questionUserKey2.setPhoneNumber(phoneNum);
									questionUserKey2
									.setQuestionUuid(question.getUuid());
									QuestionUserKey questionUserKey = questionUserService
											.getQuestionUserKeys(questionUserKey2);
									if (question.getPhoneNumber().equals(phoneNum)
											|| questionUserKey != null) {
										question.setStatus(1);// 自己公开的和查看过的
										
									} else {
										question.setStatus(2);// 没有偷看过的
									}
									String counselorDuty = question.getCounselorDuty();
									StringBuilder stringBuilder=new StringBuilder();
									if(counselorDuty!=null&&!counselorDuty.equals("")){
										String[] dutys = counselorDuty.split(",");
										for (String id : dutys) {
											if(id!=null&&!id.equals("")){
												Duty duty = counselorDutyService.getDutyById(id);
												if(duty!=null){
													
													stringBuilder.append(duty.getDutyName()+" ");
												}
											}
										}
										int i = stringBuilder.lastIndexOf(" ");
										stringBuilder.delete(i, i+1);
										question.setCounselorDuty(stringBuilder.toString());
									}
									
									List<Answer> answers = answerUserService.getAnswer(
											question.getUuid(), 2);
									if (null != answers&&answers.size()>0) {
										Answer answer = answers.get(0);
										question.setApproveNum(answer.getApproveNum());// 赞成数目
									}
									com.jieshuibao.model.db.QuestionUserExample.Criteria criteria3 = questionUserExample2
											.createCriteria();
									criteria3
									.andQuestionUuidEqualTo(question.getUuid());
									int lookNum = questionUserService
											.countUser(questionUserExample2);
									question.setLookNum(lookNum);// 看过的数量
								}
								searchResponse.setQuestions(questions);
								
							}
							
							
							List<UserSearch> users = userService.getUserSearch(pagePhone2);
							if(users!=null){
								
								for (UserSearch userSearch : users) {
									StringBuilder stringBuilder=new StringBuilder();
									String counselorDuty = userSearch.getCounselorDuty();
									if(counselorDuty!=null&&!counselorDuty.equals("")){
										String[] dutys = counselorDuty.split(",");
										for (String id : dutys) {
											if(id!=null&&!id.equals("")){
												Duty duty = counselorDutyService.getDutyById(id);
												if(duty!=null){
													
													stringBuilder.append(duty.getDutyName()+" ");
												}
											}
										}
										int i = stringBuilder.lastIndexOf(" ");
										stringBuilder.delete(i, i+1);
										userSearch.setCounselorDuty(stringBuilder.toString());
									}
								}
								searchResponse.setUserSearchs(users);
							}
							
							PolicyExample policyExample = new PolicyExample();
							policyExample.setPageIndex(0);
							policyExample.setPageSize(3);
							policyExample.setOrderByClause("createDate desc");
							Criteria createCriteria = policyExample.createCriteria();
							createCriteria.andDelFlagEqualTo(Global.SHOW);
							createCriteria.andTitleLike("%"+search+"%");
							List<Policy> policies = policyService.getPagePolicy(policyExample);
							for (Policy policy : policies) {
								String content = policy.getContent();
								if(!StringUtils.isEmpty(content)){
									String textFromHtml = DeleteHtmlUtil.getTextFromHtml(content);
									policy.setContent(textFromHtml);
								}
								policy.setExpert(null);
								policy.setOfficial(null);
								
							}
							searchResponse.setPolicies(policies);
							
							VideoExample videoExample = new VideoExample();
							videoExample.setPageIndex(0);
							videoExample.setPageSize(3);
							videoExample.setOrderByClause("createDate desc");
							com.jieshuibao.model.db.VideoExample.Criteria createCriteria2 = videoExample.createCriteria();
							createCriteria2.andDelFlagEqualTo(Global.SHOW);
							createCriteria2.andTitleLike("%"+search+"%");
							List<Video> videos = videoService.getPageVideo(videoExample);
							for (Video video : videos) {
								video.setVid("");
							}
							searchResponse.setVideos(videos);
							searchResponse.setCode(BaseRes.SUCCESS_CODE);	
						}else {
							//数据格式错误
							searchResponse.setCode("3");
							searchResponse.setDes("数据格式错误");
						}
					}else{
						//重新登录
						searchResponse.setCode("2");
						searchResponse.setDes("重新登录");
					}
						
				}else {
					//重新登录
					searchResponse.setCode("2");
					searchResponse.setDes("重新登录");
				}

			}else {
				//重新登录
				searchResponse.setCode("2");
				searchResponse.setDes("重新登录");
			}
			

			logger.info("返回：" + mapper.writeValueAsString(searchResponse));

		} catch (Exception e) {
			e.printStackTrace();
			searchResponse.setCode("0");
			searchResponse.setDes("网路繁忙");
		}
		return searchResponse;
	}
	

	//条件搜索
	
	@RequestMapping(value = "/type", method = RequestMethod.POST)
	@ResponseBody
	public Object searchType(HttpServletRequest request,
			@RequestBody PageRequest pageRequest) {
		SearchResponse searchResponse = new SearchResponse();
		try {

			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						String search = pageRequest.getSearch();
						String searchType = pageRequest.getSearchType();
						int sinceId = pageRequest.getSinceId();
						int maxId = pageRequest.getMaxId();
						int rows=0;
						if(searchType==null||searchType.equals("")){
							searchResponse.setCode("3");
							searchResponse.setDes("搜索类型错误");
							return searchResponse;
						}
						
						if(search!=null){
							
							if (sinceId <= 0) {
								sinceId = 1;
							}
							if (maxId <= 0 || maxId < sinceId) {
								maxId = sinceId;
							}
							PagePhone pagePhone2 = new PagePhone();
							pagePhone2.setSearch(search);
							pagePhone2.setPageIndex(sinceId - 1);
							pagePhone2.setPageSize(maxId - sinceId + 1);
							if(searchType.equals("article")){
								
								List<Article> articles = articelService.getArticleByTitle(pagePhone2);
								if (articles != null) {
									for (Article article : articles) {
										String descriptionHtml = article.getDescription();
										if(descriptionHtml!=null&&!descriptionHtml.equals("")){
											String description = DeleteHtmlUtil.getTextFromHtml(descriptionHtml);
											article.setDescription(description);
										}
										UserLevel userLevel = article.getUserLevel();
										if (userLevel != null) {
											String counselorDuty = userLevel
													.getCounselorDuty();
											if (counselorDuty != null
													&& !counselorDuty.equals("")) {
												if (!counselorDuty.contains(" ")) {
													StringBuilder stringBuilder = new StringBuilder();
													String[] split = counselorDuty
															.split(",");
													if(split!=null){
														
														for (String id : split) {
															if (id != null
																	&& !id.equals("")) {
																Duty duty = counselorDutyService
																		.getDutyById(id);
																if (duty != null) {
																	
																	stringBuilder
																	.append(duty
																			.getDutyName()
																			+ " ");
																}
															}
															
														}
														userLevel
														.setCounselorDuty(stringBuilder
																.toString());
													}
												}
											}
											
											article.setUserLevel(userLevel);
										}
									}
									searchResponse.setArticles(articles);
									rows=articles.size();
								}
							}else if(searchType.equals("question")){
								
								List<QuestionUserEx> questions = questionExService.getQuestionByContent(pagePhone2);
								if(questions!=null){
									
									for (QuestionUserEx question : questions) {
										QuestionUserExample questionUserExample2 = new QuestionUserExample();
										QuestionUserKey questionUserKey2 = new QuestionUserKey();
										questionUserKey2.setPhoneNumber(phoneNum);
										questionUserKey2
										.setQuestionUuid(question.getUuid());
										QuestionUserKey questionUserKey = questionUserService
												.getQuestionUserKeys(questionUserKey2);
										if (question.getPhoneNumber().equals(phoneNum)
												|| questionUserKey != null) {
											question.setStatus(1);// 自己公开的和查看过的
											
										} else {
											question.setStatus(2);// 没有偷看过的
										}
										String counselorDuty = question.getCounselorDuty();
										StringBuilder stringBuilder=new StringBuilder();
										if(counselorDuty!=null&&!counselorDuty.equals("")){
											String[] dutys = counselorDuty.split(",");
											for (String id : dutys) {
												if(id!=null&&!id.equals("")){
													Duty duty = counselorDutyService.getDutyById(id);
													if(duty!=null){
														
														stringBuilder.append(duty.getDutyName()+" ");
													}
												}
											}
											int i = stringBuilder.lastIndexOf(" ");
											stringBuilder.delete(i, i+1);
											question.setCounselorDuty(stringBuilder.toString());
										}
										
										List<Answer> answers = answerUserService.getAnswer(
												question.getUuid(), 2);
										if (null != answers&&answers.size()>0) {
											Answer answer = answers.get(0);
											question.setApproveNum(answer.getApproveNum());// 赞成数目
										}
										com.jieshuibao.model.db.QuestionUserExample.Criteria criteria3 = questionUserExample2
												.createCriteria();
										criteria3
										.andQuestionUuidEqualTo(question.getUuid());
										int lookNum = questionUserService
												.countUser(questionUserExample2);
										question.setLookNum(lookNum);// 看过的数量
									}
									searchResponse.setQuestions(questions);
									rows=questions.size();
								}
								
							}else if(searchType.equals("user")){
								List<UserSearch> users = userService.getUserSearch(pagePhone2);
								if(users!=null){
									
									for (UserSearch userSearch : users) {
										StringBuilder stringBuilder=new StringBuilder();
										String counselorDuty = userSearch.getCounselorDuty();
										if(counselorDuty!=null&&!counselorDuty.equals("")){
											String[] dutys = counselorDuty.split(",");
											for (String id : dutys) {
												if(id!=null&&!id.equals("")){
													Duty duty = counselorDutyService.getDutyById(id);
													if(duty!=null){
														
														stringBuilder.append(duty.getDutyName()+" ");
													}
												}
											}
											int i = stringBuilder.lastIndexOf(" ");
											stringBuilder.delete(i, i+1);
											userSearch.setCounselorDuty(stringBuilder.toString());
										}
									}
									searchResponse.setUserSearchs(users);
									rows=users.size();
								}
							}else if (searchType.equals("policy")){
								PolicyExample policyExample = new PolicyExample();
								policyExample.setPageIndex(pagePhone2.getPageIndex());
								policyExample.setPageSize(pagePhone2.getPageSize());
								policyExample.setOrderByClause("createDate desc");
								Criteria createCriteria = policyExample.createCriteria();
								createCriteria.andDelFlagEqualTo(Global.SHOW);
								createCriteria.andTitleLike("%"+search+"%");
								List<Policy> policies = policyService.getPagePolicy(policyExample);
								for (Policy policy : policies) {
									String content = policy.getContent();
									if(!StringUtils.isEmpty(content)){
										String textFromHtml = DeleteHtmlUtil.getTextFromHtml(content);
										policy.setContent(textFromHtml);
									}
									policy.setExpert(null);
									policy.setOfficial(null);
									
								}
								rows=policies.size();
								searchResponse.setPolicies(policies);
							}else if(searchType.equals("video")){
								VideoExample videoExample = new VideoExample();
								videoExample.setPageIndex(pagePhone2.getPageIndex());
								videoExample.setPageSize(pagePhone2.getPageSize());
								videoExample.setOrderByClause("createDate desc");
								com.jieshuibao.model.db.VideoExample.Criteria createCriteria2 = videoExample.createCriteria();
								createCriteria2.andDelFlagEqualTo(Global.SHOW);
								createCriteria2.andTitleLike("%"+search+"%");
								List<Video> videos = videoService.getPageVideo(videoExample);
								for (Video video : videos) {
									video.setVid("");
								}
								rows=videos.size();
								searchResponse.setVideos(videos);
							}else {
								searchResponse.setCode("3");
								searchResponse.setDes("搜索类型错误！");
								return searchResponse;
							}
							searchResponse.setSinceId(sinceId);
							searchResponse.setMaxId(sinceId
									+ rows - 1);
							searchResponse.setRows(rows);
							searchResponse.setCode("1");	
						}else {
							//数据格式错误
							searchResponse.setCode("3");
							searchResponse.setDes("数据格式错误");
						}
					}else{
						//重新登录
						searchResponse.setCode("2");
						searchResponse.setDes("重新登录");
					}
						
				}else {
					//重新登录
					searchResponse.setCode("2");
					searchResponse.setDes("重新登录");
				}

			}else {
				//重新登录
				searchResponse.setCode("2");
				searchResponse.setDes("重新登录");
			}
			

			logger.info("返回：" + mapper.writeValueAsString(searchResponse));

		} catch (Exception e) {
			e.printStackTrace();
			searchResponse.setCode("0");
			searchResponse.setDes("网路繁忙");
		}
		return searchResponse;
	}
	

}
